package com.wellsoft.pt.app.dingtalk.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wellsoft.context.enums.IdPrefix;
import com.wellsoft.context.jdbc.support.QueryItem;
import com.wellsoft.pt.app.dingtalk.constants.Constants;
import com.wellsoft.pt.app.dingtalk.dao.MultiOrgDingDeptDao;
import com.wellsoft.pt.app.dingtalk.entity.MultiOrgDingDept;
import com.wellsoft.pt.app.dingtalk.service.MultiOrgDingDeptService;
import com.wellsoft.pt.app.dingtalk.utils.DingtalkApiUtils;
import com.wellsoft.pt.jpa.service.impl.AbstractJpaServiceImpl;
import com.wellsoft.pt.multi.org.bean.OrgTreeNodeVo;
import com.wellsoft.pt.multi.org.entity.MultiOrgTreeNode;
import com.wellsoft.pt.multi.org.facade.service.MultiOrgService;
import com.wellsoft.pt.security.util.JwtTokenUtil;

import io.jsonwebtoken.ExpiredJwtException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Description: 钉钉部门信息service实现类
 * 
 * @author bryanlin
 * @date 2020年5月18日
 * @version 1.0
 * 
 *          <pre>
 * 修改记录:
 * 修改后版本	修改人		修改日期			修改内容
 * 2020年5月18日.1	bryanlin		2020年5月18日		Create
 *          </pre>
 *
 */
@Service
@PropertySource(value = "classpath:system-pt-dingtalk.properties")
public class MultiOrgDingDeptServiceImpl extends AbstractJpaServiceImpl<MultiOrgDingDept, MultiOrgDingDeptDao, String>
		implements MultiOrgDingDeptService {

	@Autowired
	private MultiOrgService multiOrgService;

	@Value("${pt.system_unit_id}")
	private String system_unit_id;
	@Value("${pt.system_unit_name}")
	private String system_unit_name;

	@Value("${pt.org_version_id}")
	private String org_version_id;
	@Value("${pt.org_version_name}")
	private String org_version_name;

	@Value("${pt.self_business_unit_id}")
	private String self_business_unit_id;

	@Override
	public void saveDeptFromDingtalkEventCallBack(JSONArray deptIds, String eventType) {
		for (int i = 0; i < deptIds.size(); i++) {
			String deptId = deptIds.get(i).toString();
			String accessToken = "";
			try {
				accessToken = JwtTokenUtil.getClaims(Constants.DINGTALK_ACCESS_TOKEN).toString();
			} catch (ExpiredJwtException e) { // 过期异常
				logger.error(e.getMessage());
				logger.error("----------------------重新获取access_token start--------------------");
				accessToken = DingtalkApiUtils.getAccessToken(); // 重新获取access_token
				logger.error("----------------------重新获取access_token end--------------------");
			}
			switch (eventType) {
			case "org_dept_create":// 通讯录企业部门创建
				iterateAddMultiOrgDingDept(deptId, accessToken, eventType);
				break;
			case "org_dept_modify":// 通讯录企业部门修改
				updateMultiOrgDingDept(deptId, accessToken);
				break;
			case "org_dept_remove":// 通讯录企业部门删除
				deleteMultiOrgDingDept(deptId, accessToken);
				break;
			}
		}
	}

	@Override
	public void iterateAddMultiOrgDingDept(String deptId, String accessToken, String eventType) {
		JSONObject deptObj = DingtalkApiUtils.getDingTalkDeptInfo(deptId, accessToken); // 调取钉钉接口获取部门详情
		if (deptObj != null) {
			Object parentid = deptObj.get("parentid");
			String curext = deptObj.get("ext") == null ? "" : deptObj.get("ext").toString();
			int curid = deptObj.getInt("id");
			String curname = deptObj.getString("name"); // 部门名称
			int curorder = deptObj.getInt("order"); // 部门排序
			boolean createDeptGroup = deptObj.getBoolean("createDeptGroup");
			boolean autoAddUser = deptObj.getBoolean("autoAddUser");
			String pPath = org_version_id + "/" + self_business_unit_id; // 默认
			String pname = org_version_name + "/" + system_unit_name; // 默认
			if (parentid != null && !"1".equals("" + parentid)) {// 不为空，且不为钉钉根节点
				QueryItem item = this.dao.getNodeInfoByDingtalkDeptId((int) parentid);
				if (item == null) { // 平台未查询到父节点，则通过接口调取父节点信息，先新增父节点信息
					// 递归
					iterateAddMultiOrgDingDept("" + parentid, accessToken, eventType);// 保存父的父的父。。。
				} else {
					pPath = item.getString("path");
					pname = item.getString("name");
				}
			}
			addMultiOrgDingDept(curname, "" + curid, curorder, "" + parentid, pPath, pname, curext,
					createDeptGroup, autoAddUser, IdPrefix.DEPARTMENT.getValue());
		} else {
			logger.error("--------------------未能获取对应部门信息，无法同步对应部门【%s】数据！------------------------------", deptId);
		}
	}

	private void deleteMultiOrgDingDept(String deptId, String accessToken) {
		MultiOrgDingDept curDingDept = this.getOne(deptId); // 获取当前节点信息
		if (curDingDept != null) {
			QueryItem item = this.dao.getNodeInfoByDingtalkDeptId(Integer.valueOf(deptId));
			String treeUuid = item.getString("uuid");
			multiOrgService.deleteOrgChildNode(treeUuid);
			this.dao.delete(curDingDept);
		}
	}

	private void updateMultiOrgDingDept(String deptId, String accessToken) {
		JSONObject deptObj = DingtalkApiUtils.getDingTalkDeptInfo(deptId, accessToken); // 调取钉钉接口获取部门详情
		if (deptObj != null) {
			Object parentid = deptObj.get("parentid");
			int curid = deptObj.getInt("id");
			String curname = deptObj.getString("name"); // 部门名称
			int curorder = deptObj.getInt("order"); // 部门排序
			MultiOrgDingDept curDingDept = this.getOne("" + curid); // 获取当前节点信息
			QueryItem curItem = this.dao.getNodeInfoByDingtalkDeptId(curid);
			if (parentid != null && !"1".equals("" + parentid)) {// 不为空，且不为钉钉根节点
				QueryItem parentItem = this.dao.getNodeInfoByDingtalkDeptId((int) parentid);
				if (parentItem != null) {
					String pPath = parentItem.getString("path");
					String pname = parentItem.getString("name");
					if (curItem != null) {
						String treeUuid = curItem.getString("uuid");
						OrgTreeNodeVo nodevo = this.multiOrgService.getOrgNodeByTreeUuid(treeUuid);
						nodevo.setName(curname);
						nodevo.setParentEleIdPath(pPath);
						nodevo.setParentEleNamePath(pname);
						nodevo.setCode("" + curorder);
						multiOrgService.modifyOrgChildNode(nodevo, false);
						if (curDingDept != null) {
							curDingDept.setName(curname);
							curDingDept.setParentId("" + parentid);
							this.dao.update(curDingDept);
						}
					}
				}
			}
		}
	}

	private void addMultiOrgDingDept(String name, String id, int order, String parentId, String parentPath,
			String parentPathName, String ext, boolean createDeptGroup, boolean autoAddUser, String deptType) {
		// 构造部门VO
		OrgTreeNodeVo nodevo = new OrgTreeNodeVo();
		nodevo.setName(name);
		nodevo.setShortName(name);
		nodevo.setCode("" + order);
		nodevo.setType(deptType); // 类型
		nodevo.setParentEleIdPath(parentPath);
		nodevo.setParentEleNamePath(parentPathName);
		nodevo.setOrgVersionId(org_version_id);
		nodevo.setSystemUnitId(system_unit_id);
		MultiOrgTreeNode node = multiOrgService.addOrgChildNode(nodevo);
		// 新增钉钉部门信息
		MultiOrgDingDept multiOrgDingDept = new MultiOrgDingDept();
		multiOrgDingDept.setId(id);
		multiOrgDingDept.setEleId(node.getEleId());
		multiOrgDingDept.setName(name);
		multiOrgDingDept.setParentId(parentId);
		multiOrgDingDept.setExt(ext);
		multiOrgDingDept.setCreateDeptGroup(createDeptGroup ? 1 : 0);
		multiOrgDingDept.setAutoAddUser(autoAddUser ? 1 : 0);
		this.dao.save(multiOrgDingDept);
	}

	@Override
	@Transactional
	public void fetchDeptFromDingtalk(JSONObject deptObj, int order, JSONArray allDepts) {
		if (deptObj != null) {
			Object parentid = deptObj.get("parentid");
			String curext = deptObj.get("ext") == null ? "" : deptObj.get("ext").toString();
			int curid = deptObj.getInt("id");
			String curname = deptObj.getString("name"); // 部门名称
			int curorder = deptObj.get("order") == null ? order : deptObj.getInt("order"); // 部门排序
			boolean createDeptGroup = deptObj.getBoolean("createDeptGroup");
			boolean autoAddUser = deptObj.getBoolean("autoAddUser");
			String pPath = org_version_id + "/" + self_business_unit_id; // 默认
			String pname = org_version_name + "/" + system_unit_name; // 默认
			if (parentid != null) {// 不为空，且不为钉钉根节点
				int pid = deptObj.getInt("parentid");
				QueryItem item = this.dao.getNodeInfoByDingtalkDeptId(pid);
				if (item != null) { // 平台未查询到父节点，则通过接口调取父节点信息，先新增父节点信息
					pPath = item.getString("path");
					pname = item.getString("name");
				}
			}
			addMultiOrgDingDept(curname, "" + curid, curorder, "" + parentid, pPath, pname, curext,
					createDeptGroup, autoAddUser, IdPrefix.DEPARTMENT.getValue());
		}
	}
}
